package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.constant.EsConstant;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.SuggestionBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;
    @Override
    public PageResult search(RequestParams params) {
        PageResult pageResult = new PageResult();
        List<HotelDoc> hotels = new ArrayList<HotelDoc>();
        SearchRequest searchRequest = new SearchRequest(EsConstant.index);
        if (params.getKey()!=null&&!"".equals(params.getKey())){
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            boolQueryBuilder.must(QueryBuilders.termQuery("name",params.getKey() ));
            if (params.getBrand()!=null) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("brand",params.getBrand()));
            }
            if (params.getCity()!=null) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("city",params.getCity()));
            }
            if (params.getMinPrice()!=null&&params.getMaxPrice()!=null) {
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gt(params.getMinPrice()).lt(params.getMaxPrice()));
            }
            if (params.getStarName()!=null){
                boolQueryBuilder.filter(QueryBuilders.termQuery("starName",params.getStarName()));
            }
            searchRequest.source().query(boolQueryBuilder);
            searchRequest.source().from((params.getPage()-1)*params.getSize()).size(params.getSize());
            searchRequest.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
            try {
                SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
                long value = search.getHits().getTotalHits().value;
                pageResult.setTotal(value);
                SearchHit[] hits = search.getHits().getHits();
                for (SearchHit hit : hits) {
                    String sourceAsString = hit.getSourceAsString();
                    HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
                    Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                    if (highlightFields!=null&&highlightFields.size()>0){
                        HighlightField highlightFieldByName = highlightFields.get("name");
                        if (highlightFieldByName!=null) {
                            String name = highlightFieldByName.getFragments()[0].toString();
                            hotelDoc.setName(name);
                        }
                        HighlightField highlightFieldByBrand = highlightFields.get("brand");
                        if (highlightFieldByBrand!=null) {
                            String brand = highlightFieldByBrand.getFragments()[0].toString();
                            hotelDoc.setBrand(brand);
                        }
                        HighlightField highlightFieldByCity = highlightFields.get("city");
                        if (highlightFieldByCity!=null) {
                            String city = highlightFieldByCity.getFragments()[0].toString();
                            hotelDoc.setCity(city);
                        }
                    }
                    hotels.add(hotelDoc);
                }
                pageResult.setHotels(hotels);
                return pageResult;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(params!=null){
            try {
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                if (params.getBrand()!=null) {
                    boolQueryBuilder.filter(QueryBuilders.matchQuery("brand",params.getBrand()));
                }
                if (params.getCity()!=null) {
                    boolQueryBuilder.filter(QueryBuilders.termQuery("city",params.getCity()));
                }
                if (params.getMinPrice()!=null&&params.getMaxPrice()!=null) {
                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gt(params.getMinPrice()).lt(params.getMaxPrice()));
                }
                if (params.getStarName()!=null){
                    boolQueryBuilder.filter(QueryBuilders.termQuery("starName",params.getStarName()));
                }
                if (params.getBrand()!=null||params.getCity()!=null||(params.getMinPrice()!=null&&params.getMaxPrice()!=null)||params.getStarName()!=null){
                    boolQueryBuilder.must(QueryBuilders.matchAllQuery());
                }
                searchRequest.source().query(boolQueryBuilder);
                SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
                long value = search.getHits().getTotalHits().value;
                pageResult.setTotal(value);
                for (SearchHit hit : search.getHits().getHits()) {
                    String sourceAsString = hit.getSourceAsString();
                    HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
                    hotels.add(hotelDoc);
                }
                pageResult.setHotels(hotels);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return pageResult;
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {

        try {
            //1.创建SearchRequest
            SearchRequest request = new SearchRequest(EsConstant.index);

            //过滤条件
            queryCondition(params, request);

            //2.聚合
            //2.1 品牌聚合
            aggByName(request, "brandAgg", "brand", 10);
            //2.2 星级聚合
            aggByName(request, "starNameAgg", "starName", 10);
            //2.3 城市聚合
            aggByName(request, "cityAgg", "city", 10);

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //3.处理结果
            Map<String, List<String>> resultMap = new HashMap<>();

            List<String> brandList = getListByAggName(response, "brandAgg");
            resultMap.put("brand", brandList);

            List<String> cityList = getListByAggName(response, "cityAgg");
            resultMap.put("city", cityList);

            List<String> starNameList = getListByAggName(response, "starNameAgg");
            resultMap.put("starName", starNameList);

            return resultMap;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }

    /**
     * 根据聚合名称获取结果【集合】
     * @param response
     * @param aggName
     * @return
     */
    private List<String> getListByAggName(SearchResponse response, String aggName) {
        List<String> list = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        Terms brandAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : brandAggBuckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        return list;
    }

    /**
     * 桶聚合条件
     * @param request
     * @param aggName 聚合名称
     * @param fieldName 聚合字段
     * @param size 获取条数
     */
    private void aggByName(SearchRequest request, String aggName, String fieldName, Integer size) {
        request.source()
                .size(0)
                .aggregation(
                        AggregationBuilders
                                .terms(aggName)
                                .field(fieldName)
                                .size(size)
                );
    }

    /**
     * 处理结果
     * @param response
     * @return
     */
    private List<HotelDoc> handleResponse(SearchResponse response) {
        List<HotelDoc> hotelDocList = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();

            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //获取距离
            Object[] sortValues = hit.getSortValues();
            //从当前业务角度来说，应该是最后一个元素
            if(sortValues != null && sortValues.length > 0) {
                Object distance = sortValues[sortValues.length - 1];
                //把距离设置到HotelDoc
                hotelDoc.setDistance(distance);
            }

            hotelDocList.add(hotelDoc);
        }
        return hotelDocList;
    }

    /**
     * 封装查询条件
     * @param params
     * @param request
     */
    private void queryCondition(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //搜索框 all
        String key = params.getKey();
        if(key != null && !"".equals(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        //品牌
        String brand = params.getBrand();
        if(brand != null && !"".equals(brand)) {
            boolQuery.must(QueryBuilders.termQuery("brand", brand));
        }

        //城市
        String city = params.getCity();
        if(city != null && !"".equals(city)) {
            boolQuery.must(QueryBuilders.termQuery("city", city));
        }

        //星级
        String starName = params.getStarName();
        if(starName != null && !"".equals(starName)) {
            boolQuery.must(QueryBuilders.termQuery("starName", starName));
        }

        //价格
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if(minPrice != null && maxPrice != null) {
            boolQuery.filter(
                    QueryBuilders.rangeQuery("price")
                            .gte(minPrice)
                            .lte(maxPrice)
            );
        }

        //做广告：为isAD是true的酒店增加分数
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQuery,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(100)
                                )
                        })
                        //算分方式，现在是求和
                        .boostMode(CombineFunction.SUM);
        //2.1.2 封装查询条件
        request.source().query(functionScoreQuery);

    }

    @Override
    public List<String> suggestion(String key) {
        try {
            //1、准备SearchRequest
            SearchRequest request = new SearchRequest(EsConstant.index);

            //2、准备DSL
            request.source().suggest(
                    new SuggestBuilder()
                            //String name, SuggestionBuilder<?> suggestion
                            .addSuggestion(
                                    "hotel_suggest",
                                    new CompletionSuggestionBuilder("suggestion")
                                            .prefix(key)
                                            .skipDuplicates(true)
                                            .size(10)
                            )
            );

            //3、发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //4、解析结果
            List<String> resultList = new ArrayList<>();
            CompletionSuggestion suggestion = response.getSuggest().getSuggestion("hotel_suggest");
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                resultList.add(text);
            }
            return resultList;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new ArrayList<>();
    }
}

